#!/use/bin/python
# coding=utf-8
# 早间开机 数据分析-追剧提醒-服务推送数量
import datetime
import pymysql

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql):
    conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        if numResult[0] is not None:
            num = numResult[0]
    return num


#根据月份 获取本月指定指标的 总和
#tableName 指定的报表
#columnName 指定的指标字段
#date 月份
def getSumNumByTableColumnNameAndDate(tableName,columnName,date):
    conn, cur = getDataConnection()
    selectNumSql = f"""
                     select sum({columnName}) from {tableName} t where 1=1   
                     """;
    if len(date) >0:
        selectNumSql = f"""{selectNumSql} and SUBSTR( t.ref_date, 1,7) = '{date}' and LENGTH(t.ref_date) = 10  """
    cur.execute(selectNumSql)
    #print(selectNumSql);
    numResult = cur.fetchone()
    num = 0
    if numResult!= None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

# 记录 数据分析-早间开机-服务推送数量 analysis_zjtx_push_num
def insertPushNum(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_zjtx_push_num 表是否已经存在当天 数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_zjtx_push_num t where 1=1  and t.ref_date =  '{date}'")
        #生活助手后台接收到推送
        webReceiverNum = selectNumBySql(
            f"select sum(t.device_num) from log_device_push t where t.scene = 1 and   DATE_FORMAT(t.create_time, '%Y-%m-%d') ='{date}'")
        # 生活助手后台推送追剧
        webPushNum = selectNumBySql(
            f"select sum(t.device_num) from log_device_push t where  t.scene = 1 and t.push_status = 1 and   DATE_FORMAT(t.create_time, '%Y-%m-%d') ='{date}';")
        # 客户端接收
        clientReceiverNum = selectNumBySql(
            f"select count(1) from log_common_service t where t.`key` = 'suAutoOpenScreen' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}'")
        # 消息等待展示
        waitShowNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service t where t.`key` = 'suNewsWaitShow' and DATE_FORMAT(t.create_time, '%Y-%m-%d') ='{date}'")
        # 消息等待展示设备中触发用户回家
        userGohomeNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service t where t.`key` = 'userGoHome' and DATE_FORMAT(t.create_time, '%Y-%m-%d') ='{date}'")
        # 获取当日追剧提醒 展示次数
        newPushNum = selectNumBySql(
            f"select count(1) from log_common_service t where t.`key` = 'suAutoOpenScreen' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}'")
        # 获取当日追剧提醒 展示设备量(去重)
        newActiveIdNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service t where t.`key` = 'suAutoOpenScreen' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}'")


        if countNum == 0:
            logDetail =f"{date}日新增-生活助手后台接收到推送{webReceiverNum},生活助手后台推送追剧{webPushNum},客户端接收{clientReceiverNum},消息等待展示{waitShowNum}," \
                       f"\n消息等待展示设备中触发用户回家{userGohomeNum},获取当日追剧提醒展示次数{newPushNum},获取当日追剧提醒展示设备量(去重){newActiveIdNum}"
            print(logDetail)
            # 插入追剧提醒推送成功率
            insertSql = f"""insert into analysis_zjtx_push_num(web_receiver_num,web_push_num,client_receiver_num,wait_show_num,user_gohome_num,zjkj_show_num,zjkj_show_device_num,ref_date) 
                value({webReceiverNum},{webPushNum},{clientReceiverNum},{waitShowNum},{userGohomeNum},{newPushNum},{newActiveIdNum},'{date}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{date}日新增-生活助手后台接收到推送{webReceiverNum},生活助手后台推送追剧{webPushNum},客户端接收{clientReceiverNum},消息等待展示{waitShowNum}," \
                        f"\n消息等待展示设备中触发用户回家{userGohomeNum},获取当日追剧提醒展示次数{newPushNum},获取当日追剧提醒展示设备量(去重){newActiveIdNum}"
            print(logDetail)
            # 更新追剧提醒推送成功率
            updateSql = f"""
                update analysis_zjtx_push_rate set web_receiver_num = {webReceiverNum} ,web_push_num = {webPushNum},client_receiver_num = {clientReceiverNum},wait_show_num={waitShowNum} ,user_gohome_num={userGohomeNum},
                zjkj_show_num = {newPushNum} ,zjkj_show_device_num = {newActiveIdNum} ,update_time = now()  where  ref_date = '{date}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 49
        jobName = '核心指标-追剧提醒-服务推送数量'
        tableName = 'analysis_zjtx_push_rate'
        # 插入日志表
        saveLogSql = f"""insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value({jobId},'{jobName}','{detail}','{tableName}','{ref_date}')"""
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    date = getdate(d)
    monthdate = getMonthdate(d)
    print (f"{date}日期,更新<数据分析-追剧提醒-服务推送数量>报表")
    insertPushNum(date)

